<template>
  <div>
    <el-form :model="uploadForm" ref="uploadForm" label-width="130px" size="large"
             :label-position="'right'" :rules="rules"
             style="margin-top: 20px;margin-left: 20px;margin-right: 80px">
      <!--底部广告-->
      <!--指引明确，收益最大化-->
      <el-form-item label="广告类型：" prop="adType">
        <el-row v-if="uploadForm.adType === 1">
          底部广告
          <el-popover
              placement="right"
              title="底部广告说明"
              :width="250"
              trigger="hover"
              content="广告展示在底部，点击广告后跳转到指定链接。按点击次数支付，当余额不足时，将暂停广告投放，直到余额恢复。">
            <template #reference>
              <div style="margin-top: 2px;margin-left: 5px">
                <el-icon color="#a1a1a1"><Warning /></el-icon></div>
            </template>
          </el-popover>
          <el-popover
              placement="right"
              title="开屏广告说明"
              :width="250"
              trigger="hover">
            <div>
              <p>当用户打开软件时，在用户打开应用或网站时出现在屏幕上，可以展示给更多的用户，从而达到更好的效果(๑•̀ㅂ•́)و✧</p>
              <p style="color: #76cb02">点击即可选择开屏广告</p>
            </div>
            <template #reference>
              <el-link type="primary" style="margin-left: 8px" @click="uploadForm.adType = 2">想要更好的展示效果吗| ू•ૅω•́)？</el-link>
            </template>
          </el-popover>
        </el-row>
        <el-row v-if="uploadForm.adType === 2">
          开屏广告
          <el-popover
              placement="right"
              title="开屏广告说明"
              :width="250"
              trigger="hover">
            <div>
              <p>当用户打开软件时，在用户打开应用或网站时出现在屏幕上，可以展示给更多的用户，从而达到更好的效果(๑•̀ㅂ•́)و✧</p>
            </div>
            <template #reference>
              <div style="margin-top: 2px;margin-left: 5px">
                <el-icon color="#a1a1a1"><Warning /></el-icon></div>
            </template>
          </el-popover>
          <el-popover
              placement="right"
              title="开屏广告说明"
              :width="250"
              trigger="hover">
            <div>
              <p>广告展示在底部，点击广告后跳转到指定链接。按点击次数支付，当余额不足时，将暂停广告投放，直到余额恢复。</p>
              <p style="color: #76cb02">点击即可选择底部广告</p>
            </div>
            <template #reference>
              <el-link type="primary" style="margin-left: 8px" @click="uploadForm.adType = 1">还是底部广告吧( •̥́ ˍ •̀ू )</el-link>
            </template>
          </el-popover>
        </el-row>
      </el-form-item>
      <div v-if="uploadForm.adType == 1">
        <el-form-item :class="{ hide: hideUpload }" label="底部图片" prop="bottomImg">
          <el-upload
              ref="upload"
              action="#"
              multiple
              :limit="limit"
              :file-list="uploadForm.bottomImgList"
              list-type="picture-card"
              :on-preview="handleBottomPreview"
              :on-change="bottomOnChange"
              :on-remove="bottomRemove"
              :on-exceed="handleExceed"
              accept="image/jpeg,image/png"
              :auto-upload="false">
            <svg t="1708595840001" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"
                 p-id="4203" width="50" height="50"><path d="M914.618182 477.090909H546.909091V109.381818c0-18.618182-16.290909-34.909091-34.909091-34.909091s-34.909091 16.290909-34.909091 34.909091v367.709091H109.381818c-18.618182 0-34.909091 16.290909-34.909091 34.909091s16.290909 34.909091 34.909091 34.909091h367.709091v367.709091c0 18.618182 16.290909 34.909091 34.909091 34.909091s34.909091-16.290909 34.909091-34.909091V546.909091h367.709091c18.618182 0 34.909091-16.290909 34.909091-34.909091s-16.290909-34.909091-34.909091-34.909091z" fill="#8a8a8a" p-id="4204"></path></svg>
          </el-upload>
          <el-link :underline="false" @click="dialogVisible=true"
                   type="primary" style="margin-left: 10px">效果预览</el-link>
        </el-form-item>
        <el-form-item :class="{ hide: hideUpload }" label="详情页图片" prop="detailImg">
          <el-upload
              ref="upload"
              action="#"
              multiple
              :limit="limit"
              :file-list="uploadForm.detailImgList"
              list-type="picture-card"
              :on-preview="handleDetailPreview"
              :on-change="detailOnChange"
              :on-remove="detailRemove"
              :on-exceed="handleExceed"
              accept="image/jpeg,image/png"
              :auto-upload="false">
            <svg t="1708595840001" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"
                 p-id="4203" width="50" height="50"><path d="M914.618182 477.090909H546.909091V109.381818c0-18.618182-16.290909-34.909091-34.909091-34.909091s-34.909091 16.290909-34.909091 34.909091v367.709091H109.381818c-18.618182 0-34.909091 16.290909-34.909091 34.909091s16.290909 34.909091 34.909091 34.909091h367.709091v367.709091c0 18.618182 16.290909 34.909091 34.909091 34.909091s34.909091-16.290909 34.909091-34.909091V546.909091h367.709091c18.618182 0 34.909091-16.290909 34.909091-34.909091s-16.290909-34.909091-34.909091-34.909091z" fill="#8a8a8a" p-id="4204"></path></svg>
          </el-upload>
          <el-link :underline="false" @click="detailDialogVisible=true"
                   type="primary" style="margin-left: 10px">效果预览</el-link>
        </el-form-item>
      </div>
      <div v-if="uploadForm.adType==2">
        <el-form-item label="生源地关键词：" prop="nativePlace">
          <el-select
              v-model="uploadForm.nativePlace"
              size="large"
              style="width: 450px" clearable
              placeholder="请选择生源地关键词"
              @change="fetchTotalStudent">
            <el-option
                v-for="item in nativeList"
                :key="item.id"
                :label="item.province"
                :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="学院关键词：" prop="collegeId">
          <el-select
              v-model="uploadForm.collegeId"
              size="large"
              style="width: 450px" clearable
              placeholder="请选择学院关键词"
              @change="fetchTotalStudent">
            <el-option
                v-for="item in collegeList"
                :key="item.collegeId"
                :label="item.collegeName"
                :value="item.collegeId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="性别关键词：" prop="gender">
          <el-select
              v-model="uploadForm.gender"
              size="large"
              style="width: 450px" clearable
              placeholder="请选择性别关键词"
              @change="fetchTotalStudent">
            <el-option
                v-for="item in genderList"
                :key="item.genderId"
                :label="item.genderName"
                :value="item.genderId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :class="{ hide: hideUpload }" label="开屏广告图片" prop="openScreenImg">
          <el-upload
              ref="upload"
              action="#"
              multiple
              :limit="limit"
              :file-list="uploadForm.openScreenImg"
              list-type="picture-card"
              :on-preview="handleOpenScreenPreview"
              :on-change="openScreenOnChange"
              :on-remove="openScreenRemove"
              :on-exceed="handleExceed"
              accept="image/jpeg,image/png"
              :auto-upload="false">
            <svg t="1708595840001" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"
                 p-id="4203" width="50" height="50"><path d="M914.618182 477.090909H546.909091V109.381818c0-18.618182-16.290909-34.909091-34.909091-34.909091s-34.909091 16.290909-34.909091 34.909091v367.709091H109.381818c-18.618182 0-34.909091 16.290909-34.909091 34.909091s16.290909 34.909091 34.909091 34.909091h367.709091v367.709091c0 18.618182 16.290909 34.909091 34.909091 34.909091s34.909091-16.290909 34.909091-34.909091V546.909091h367.709091c18.618182 0 34.909091-16.290909 34.909091-34.909091s-16.290909-34.909091-34.909091-34.909091z" fill="#8a8a8a" p-id="4204"></path></svg>
          </el-upload>
          <el-link :underline="false" @click="openScreenDialogVisible=true"
                   type="primary" style="margin-left: 10px">效果预览</el-link>
        </el-form-item>
      </div>
      <el-form-item style="text-align: center">
        <el-button size="medium" @click="handlePrev">上一步，填写基础信息</el-button>
        <el-button type="primary" size="medium" @click="handleFinishCommit">完成，提交广告</el-button>
      </el-form-item>
    </el-form>
    <!-- 底部广告效果预览 -->
    <div>
      <el-dialog
          v-model="dialogVisible"
          center title="效果预览"
          width="25%">
        <el-main>
          <div class="block">
            <div style="position: relative; width: 224px; height: 485px;
            justify-content: center;align-items: center;">
              <el-image
                  style="width: 224px; height: 485px; position: relative; z-index: 1;"
                  :src="phoneUrl">
              </el-image>
              <el-image
                  style="width: 210px; height: 439px;top:24px;
                position: absolute;z-index:2;left: 7px;" :src="bottomUrl">
              </el-image>
              <el-image v-if="bottomImageUrl"
                        style="width: 189px; height: 47px; position: absolute; top: 374px; left: 17px; z-index: 3;border-radius: 5%"
                        :src="bottomImageUrl">
              </el-image>
            </div>
          </div>
        </el-main>
      </el-dialog>
    </div>
    <!-- 广告详情效果预览 -->
    <div>
      <el-dialog
          v-model="detailDialogVisible"
          center title="效果预览"
          width="25%">
        <el-main>
          <el-text style="color: #76cb02;">单击实现页面移动效果，双击取消</el-text>
          <div class="block" style="margin-top: 10px">
            <div style="position: relative; width: 224px; height: 485px; justify-content: center; align-items: center; overflow: hidden; position: relative;">
              <el-image
                  style="width: 224px; height: 485px; position: relative; z-index: 1;"
                  :src="phoneUrl">
              </el-image>
              <div class="image-container"
                   style="position: absolute; top:23px; left:0px; z-index: 2;"
                   @click="handleMouseDown"
                   @dblclick="handleMouseUp"
                   @mousemove="handleMouseMove">
                <div class="image-view"
                     style="top: 50px; left: 7px;"
                     ref="imageView">
                  <img class="full-size-image"
                       :src="fullSizeImageUrl"/>
                </div>
              </div>
              <el-image
                  style="width: 210px; height: auto; position: absolute;top: 23px; left: 7px;
                 z-index: 3;"
                  :src="head">
              </el-image>
            </div>
          </div>
        </el-main>
      </el-dialog>
    </div>
    <!-- 开屏广告效果预览 -->
    <div>
      <el-dialog
          v-model="openScreenDialogVisible"
          center title="效果预览"
          width="25%">
        <el-main>
          <div class="block">
            <div style="position: relative; width: 224px; height: 485px;
            justify-content: center;align-items: center;">
              <el-image
                  style="width: 224px; height: 485px; position: relative; z-index: 1;"
                  :src="phoneUrl">
              </el-image>
              <el-image v-if="openScreenImageUrl"
                        style="width: 210px; height: 439px;top:24px;position: absolute;z-index:2;left: 7px;"
                        :src="openScreenImageUrl">
              </el-image>
              <el-image
                  style="width: 49px; height: 27px; position: absolute;top: 425px; left: 155px;
                 z-index: 3;"
                  :src="skip">
              </el-image>
            </div>
          </div>
        </el-main>
      </el-dialog>
    </div>
  </div>

</template>
<script>
import axios from "axios";
import {ElMessage} from "element-plus";
import bottomUrl from "@/assets/ad/bottomAd.png";
import phoneUrl from "@/assets/ad/phoneImg.png";
import skip from "@/assets/ad/skip.png"
import head from "@/assets/ad/head.png"
export default {
  name: "AdPicUpload",
  props:{
    addInfo:{
      type:Object
    }
  },
  data() {
    return {
      uploadForm:{
        adType:1,
        bottomImgList:[],
        detailImgList:[],
        openScreenImg: [],
        bottomUrl:'',
        nativePlace:"",
        collegeId:"",
        gender:"",
      },
      collegeList: [],
      genderList: [{genderId:1,genderName:"男"},{genderId:2,genderName:"女"}],
      nativeList: [],
      rules: {
        bottomImg: [
          { required: true, message: '请上传底部广告图片', trigger: 'blur' }
        ],
        detailImg: [
          { required: true, message: '请上传广告详情图片', trigger: 'blur' }
        ],
        openScreenImg: [
          { required: true, message: '请上传开屏广告图片', trigger: 'blur' }
        ],
        adType: [
          { required: true, message: '请输入广告名称', trigger: 'blur' }
        ]
      },
      limit: 1,
      visible: false,
      hideUpload: false, //是否显示上传图片的加号
      //底部图片参数
      bottomUploadUrl: "",
      bottomImageUrl: "",
      bottomVisible: false,
      deleteBottomImgFileList: [],
      //详情图片参数
      detailUploadUrl: "",
      detailImageUrl: "",
      detailVisible: false,
      deleteDetailImgFileList: [],
      //开屏广告图片参数
      openScreenUploadUrl: "",
      openScreenImageUrl: "",
      openScreenVisible: false,
      deleteOpenScreenImgFileList: [],
      //弹窗
      phoneUrl:phoneUrl,
      bottomUrl: bottomUrl,
      skip:skip,
      dialogVisible:false,
      openScreenDialogVisible:false,
      detailDialogVisible:false,
      head:head,
      fullSizeImageUrl:"", // 替换为实际的图片 URL
      isDragging: false,
      startY: 0,
      offsetY: 0,
      selectedStudent:0,
    };
  },
  methods: {
    //返回上一步
    handlePrev(){
      this.$emit('prevStep')
    },
    //提交广告
    handleFinishCommit(){
      console.log("提交广告",this.uploadForm.bottomImgList)
      console.log("调用handleFinishCommit")
      let addData;
      if(this.uploadForm.adType==1){
        addData = this.addUploadInfo(this.uploadForm.adType,this.uploadForm.bottomImgList,this.uploadForm.detailImgList,null,null,null,0)
      }else if(this.uploadForm.adType==2){
        addData = this.addUploadInfo(this.uploadForm.adType,this.uploadForm.openScreenImg,null,
            this.uploadForm.nativePlace,this.uploadForm.collegeId,this.uploadForm.gender,this.selectedStudent)
      }
      console.log("ADD:",addData)
      this.$emit('getTaskDetail',addData)
      this.$emit('finishCommit');
    },
    async getNativeList() {
      try {
        const res = await axios.get('/region/provinces');
        if (res.status === 200) {
          this.nativeList = res.data.data;
          console.log("itemList返回值",this.nativeList);
        } else {
          ElMessage('获取学生籍贯数据失败');
        }
      } catch (error) {
        console.error('Error fetching data:', error);
        ElMessage('获取学生籍贯数据失败');
      }
    },
    async getCollegeList() {
      try {
        const res = await axios.get('/selectorManage/getCollegeList');
        if (res.status === 200) {
          this.collegeList = res.data.data;
        } else {
          ElMessage('获取学生学院数据失败');
        }
      } catch (error) {
        console.error('Error fetching data:', error);
        ElMessage('获取学生学院数据失败');
      }
    },
    fetchData(nativePlace,collegeId, gender){
      return{
        "nativePlace":nativePlace, "collegeId":collegeId, "gender":gender
      };
    },
    async fetchTotalStudent() {
      let studentData = this.fetchData(this.uploadForm.nativePlace,this.uploadForm.collegeId, this.uploadForm.gender);
      console.log('当前学生数据',studentData)
      const response = await axios.post('/adManage/getTotalStudent',studentData);
      console.log("获取学生人数结果",response);
      console.log("获取学生人数",response.data);
      this.selectedStudent = response.data;
    },

    //定义新增数据
    addUploadInfo(adType,imageUrl,detailUrl,nativePlace,collegeId,gender,selectedStudent){
      return {
        "adType":adType,"imageUrl":imageUrl, "detailUrl": detailUrl,"nativePlace":nativePlace,
        "collegeId":collegeId,"gender":gender,selectedStudent:selectedStudent
      };
    },
    /*底部图片*/
    //预览图片时
    handleBottomPreview(file) {
      this.bottomImageUrl = file.url;
      this.bottomVisible = true;
      console.log("预览图片时")
    },
    bottomOnChange(file) {
      console.log("效果预览")
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      this.uploadForm.bottomImgList.push(file);
      this.bottomImageUrl = file.url;
    },
    //删除图片时
    bottomRemove(file) {
      if (file.id) {
        console.log("删除了已被上传过的图片");
        console.log(file.id);
        this.deleteBottomImgFileList.push(file.id);
      }
    },
    /*详情图片*/
    //
    handleMouseDown(event) {
      this.isDragging = true;
      this.startY = event.clientY - this.offsetY;
    },
    handleMouseUp() {
      this.isDragging = false;
    },
    handleMouseMove(event) {
      if (this.isDragging) {
        //let deltaY = event.clientY - this.startY;
        //this.$refs.imageView.style.top = this.offsetY + deltaY + 'px';
        this.offsetY = event.clientY - this.startY;
        this.$refs.imageView.style.transform = `translate(0, ${this.offsetY}px)`;
      }
    },
    //预览图片时
    handleDetailPreview(file) {
      this.detailImageUrl = file.url;
      this.detailVisible = true;
      console.log("预览图片时")
    },
    detailOnChange(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      this.uploadForm.detailImgList.push(file);
      this.fullSizeImageUrl = file.url;

    },
    //删除图片时
    detailRemove(file) {
      if (file.id) {
        console.log("删除了已被上传过的图片");
        console.log(file.id);
        this.deleteDetailImgFileList.push(file.id);
      }
    },
    /*开屏广告图片*/
    //点击上传图片
    submitUpload() {
      let formData = new FormData();
      let addData = this.addClothingInfo(this.uploadForm.clothingName, this.uploadForm.type, this.uploadForm.gender);

      this.uploadForm.imgFileList.forEach((file) => {
        formData.append("file", file.raw);
      });

      formData.append("addData", JSON.stringify(addData)); // 将 addData 添加到 formData 中

      axios.post('/clothingManage/addClothing', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
          .then(response => {
            // 处理后端返回的数据
            if (response.status === 200) {
              ElMessage({
                message: '添加成功',
                type: 'success',
              });
              this.resetForm('uploadForm');
              this.uploadForm.imgFileList = [];
            }
          })
          .catch(error => {
            // 处理错误情况
            console.log(error);
            this.$message.error();
          });
    },
    //预览图片时
    handleOpenScreenPreview(file) {
      this.openScreenImageUrl = file.url;
      this.openScreenVisible = true;
      console.log("预览图片时")
    },
    openScreenOnChange(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      this.uploadForm.openScreenImg.push(file);
      this.openScreenImageUrl = file.url;
    },
    //删除图片时
    openScreenRemove(file) {
      if (file.id) {
        console.log("删除了已被上传过的图片");
        console.log(file.id);
        this.deleteOpenScreenImgFileList.push(file.id);
      }
    },
    //文件超出个数限制时
    handleExceed() {
      this.$message.warning(
          `当前限制选择 1 个文件`
      );
    },
    handleCommodityPicSuccess(res) {
      if (res && res.code === 200) {
        this.$message.success('上传成功');
      } else if (res && res.message) {
        this.$message.error(res.message);
      } else {
        this.$message.error('上传失败，未知错误');
      }
    },
  },
  mounted() {
    this.getNativeList();
    this.getCollegeList();
    // 获得图片的真实尺寸
    const image = new Image();
    image.src = this.fullSizeImageUrl;
    image.onload = () => {
      this.imageWidth = image.width;
      this.imageHeight = image.height;
    };
  },
}
</script>
<style scoped>
.image-container {
  position: absolute;
  width: 217px; /* 设置框的宽度 */
  height: 440px; /* 设置框的高度 */
  overflow: hidden;
}

.image-view {
  position: absolute;
  width: 217px;
  height: auto;
  overflow: hidden;
  transform: translateY(0);
  transition: transform 0.3s ease-out;
}

.full-size-image {
  width: 100%; /* 图片宽度与框的宽度相同 */
  height: auto; /* 图片长度根据宽度同比例缩放 */
}

.card {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 120%;
}
.card .cardImg {
  height: 100%;
  position: absolute;
  top: 0;
  right: 0;
  cursor: grab;
}
</style>